﻿//微信文章编辑器
var dblclick = "click";
var k_obj;
var p_obj;
var parent_obj;
var clickdom = 0;

function showlog(msg) {
    if (console) {
        console.log(new Date() + ">>"+msg);
    }
}

$(function () {
    checkClick();
    addBodyEvent();
   
    addSaveButton();
    addTool();
});

function addSaveButton() {
    //插入一个固定的按钮
    var divx = "<div class='adsavewenzhang d_z'>保存</div>";
    $("body").append($(divx));
    $(divx).show();

    $(document).on(dblclick, ".adsavewenzhang", adsavewenzhang);
}

//增加一个工具层
function addTool() {
    var divx = "<div class='adtools clearfix d_z'></div>";
    $("body").append($(divx));
    $(divx).hide();
}

function getTools() {
    return $(".adtools");
}

//加载菜单数据
function showTool(flag) {

    var y = p_obj.offset().top;
    var h = p_obj.outerHeight(true);

    if(flag)//全屏模式
    {
        getTools().addClass("adtools100");
        getTools().height($(window).height());
        getTools().css({ top:0, left: 0 });
    }else
    {
        getTools().removeClass("adtools100");
        getTools().width(($("body").width() - 15 * 2 - 2 - 4 * 2));
        getTools().css({ top: y + h + 2, left: 0 });
    }

    getTools().show();
    getMenu().hide();
}

//保存信息
function adsavewenzhang(event) {
    event.stopPropagation();
    getMenu().remove();
    $(".adsavewenzhang").remove();
    $(".adtools").remove();
    
    var html = $("body").html();
    $.post("/savebody",
        { content: html, u: g_code },
        function (ret) {
            location.href = "/s?u=" + g_code;
        });
}

function checkClick() {
    var system = {
        win: false,
        mac: false,
        xll: false
    };
    var p = navigator.platform;
    system.win = p.indexOf("Win") !=-1;
    system.mac = p.indexOf("Mac") != -1;
    system.x11 = (p == "X11") || (p.indexOf("Linux") != -1);
    if (system.win || system.mac || system.xll) {
        dblclick = "click";
    } else {
        dblclick = "touchend"
    }
}

var domNode = "div,p,img,h1,h2,h3,h4,h5,h6,span,input,textarea,iframe,em,a";

function addBodyEvent() {
    $(domNode).each(function () {
        StartbindElementEvent($(this));
    });
    //$(document).on("touchstart", domNode,
    //function (event) {
    //    //只有1的时候或者0的时候才触发
    //    clickdom = 1;
    //    event.stopPropagation();
    //});

    //$(document).on("touchmove", domNode,
    //function (event) {
    //    clickdom = 2;//拖动的时候不要触发
    //    event.stopPropagation();
    //});

    //$(document).on(dblclick, domNode,bindElementEvent);
}

function StartbindElementEvent(ths) {
    ths.bind("touchstart",
        function (event) {
            //只有1的时候或者0的时候才触发
            clickdom = 1;
            event.stopPropagation();
        });

    ths.on("touchmove",
    function (event) {
        clickdom = 2;//拖动的时候不要触发
        event.stopPropagation();
    });

    ths.on(dblclick, bindElementEvent);
}

function bindElementEvent(event) {
    event.stopPropagation();
    if (!checkMenu($(this)) && clickdom != 2) {
        k_obj = $(this);
        //如果触发的是同一个东西，不再重复触发
        if (k_obj == p_obj) return;

        getTools().hide();
        removeBgColor();
        p_obj = k_obj;
        showMenu();
    }
    parent_obj = $(this);
    showlog(">>>"+parent_obj[0].tagName);
}

function createMenu() {
    var div = "<div class='adeditmenu clearfix'></div>"
    //加载一个菜单层
    $("body").append($(div));

    var html = "";
    html += "<div ><span class='adbtnWenZi d_z'>插文字</span></div>";
    html += "<div ><span class='adbtnGuangGao d_z'>插广告</span></div>";
    html += "<div ><span class='adbtnQuXiao d_z'>取消</span></div>";
    html += "<div ><span class='adbtnTuPian d_z'>插图片</span></div>";
    html += "<div ><span class='adbtnShiPin d_z'>插视频</span></div>";
    html += "<div ><span class='adbtnYinYue d_z'>插音乐</span></div>";
    html += "<div ><span class='adbtnDel d_z'>删除</span></div>";
    html += "<div ><span class='adbtnPre d_z'>删前</span></div>";
    html += "<div ><span class='adbtnNext d_z'>删后</span></div>";
    getMenu().html(html);

    
    var y = p_obj.offset().top;
    var h = p_obj.outerHeight(true);
    getMenu().width(($("body").width() - 15*2-2-4*2));
    getMenu().css({top:y+h+2,left:0});
    getMenu().show();

    bindClick();
}



function bindClick() {
    $(document).on(dblclick, ".adbtnQuXiao", btnQuXiao);
    $(document).on(dblclick, ".adbtnWenZi", btnWenZi);
    $(document).on(dblclick, ".adbtnDel", btnDel);
    $(document).on(dblclick, ".adbtnPre", btnPre);
    $(document).on(dblclick, ".adbtnNext", btnNext);

    $(document).on(dblclick, ".adbtnTuPian", btnTuPian);
    $(document).on(dblclick, ".adbtnGuangGao", btnGuangGao);
    $(document).on(dblclick, ".adbtnShiPin", btnShiPin);
    $(document).on(dblclick, ".adbtnYinYue", btnYinYue);
}

function addBgColor() {
    p_obj && p_obj.length > 0 && p_obj.addClass("adedit_bg");
}

function removeBgColor() {
    p_obj && p_obj.length > 0 && p_obj.removeClass("adedit_bg");
    getMenu() && getMenu().length > 0 && getMenu().remove();
}

function getMenu() {
    return $(".adeditmenu");
}

function checkMenu(obj) {
    //判断是不是点击到dz上面，如果是动作上面，就不要阻止事件
    return obj.hasClass("d_z") && getMenu() && getMenu().length > 0;
}

function showMenu() {
    addBgColor();

    var X = p_obj.offset().top;
    var Y = p_obj.offset().left;

    createMenu();
}

function btnQuXiao() {
    getMenu().hide();
    removeBgColor();
}

function btnWenZi() {
    showTool();
    var tools = getTools();


    var html = "";
    html += "<div class='d_z adtitle'>插入文字</div>";
    html += "<textarea class='d_z adtextarea'></textarea></br>";
    html += "<span class='d_z adbtn' data-f='webziqueding()'>确定</span>";
    html += "<span class='d_z adbtn' data-f='webziqingkong()'>清空</span>";
    html += "<span class='d_z adbtn' data-f='webzifanhui()'>返回</span></br>";
    


    html += "<span class='d_z adbtn' data-f='webzistyle(\"font-size\",\"24px\")'>最大</span>";
    html += "<span class='d_z adbtn' data-f='webzistyle(\"font-size\",\"18px\")'>正常</span>";
    html += "<span class='d_z adbtn' data-f='webzistyle(\"font-size\",\"14px\")'>最小</span></br>";

    html += "<span class='d_z adbtn' data-f='webzistyle(\"text-align\",\"left\")'>左对齐</span>";
    html += "<span class='d_z adbtn' data-f='webzistyle(\"text-align\",\"center\")'>居中</span>";
    html += "<span class='d_z adbtn' data-f='webzistyle(\"text-align\",\"right\")'>右对齐</span></br>";

    var color = "000000,FF0000,00FF00,0000FF,FF00FF,00DB00,F9F900,984B4B,9F4D95,00CACA,0000C6,5B00AE";
    $(color.split(',')).each(function (k,v) {
        html += "<span class='d_z adbtn' data-f='webzistyle(\"color\",\"#" + v + "\")' style='background-color:#" + v + "'>#" + v + "</span>";
    });
   
    

    tools.empty();
    tools.html(html);
    bindWenZiClick();
}

function bindWenZiClick() {
    $(".adbtn").unbind(dblclick);
    $(".adbtn").bind(dblclick, function (event) {
        event.stopPropagation();

        var ths = $(this);
        var fun = ths.attr("data-f") || "";
        if (fun != "") eval(fun);
    });

    $("input[type='file']").unbind("change");
    $("input[type='file']").bind("change", uploadfile);
}

function webzistyle(k,v) {
    var content = getContent();
    content.css(k,v);
}

function webzifanhui() {
    getMenu().show();
    getTools().hide();
}

function webziqingkong() {
    var content = getContent();
    content.val("");
}

function webziqueding() {
    getMenu().hide();
    getTools().hide();

    removeBgColor();

    var content = getContent();
    var text = content.val();
    var span = p_obj.clone(true);
    
    span.css("font-size", content.css("font-size"));
    span.css("text-align", content.css("text-align"));
    span.css("color", content.css("color"));

    //加一个换行
    span.html(text+"</br>");
    //插入内容
    p_obj.before(span);
    StartbindElementEvent(span);
}

function shipinqueding() {
    getMenu().hide();
    getTools().hide();

    removeBgColor();

    var content = getContent();
    var text = content.val();

    //<embed src="' + text + '" allowFullScreen="true" quality="high" width="100%" height="300" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash"></embed>
    if (text.indexOf("http")!=-1) {
        var span = $('<div>'+text+'</div>');
       
        //插入内容
        p_obj.before(span);
        StartbindElementEvent(span);
    }
}


function yinyuequeding() {
    var content = $(".adyinyue").val();
    yinyueqingkong();

    $("body").append($("<audio src='http://thirdparty.gtimg.com/"+content+".m4a?fromtag=38' autoplay='autoplay' loop='loop'>"));
}


function yinyueqingkong() {
    getMenu().hide();
    getTools().hide();
    removeBgColor();
    $("audio").remove();
}

function getContent() {
    return $(".adtextarea");
}

function btnYinYue() {
    showTool(true);
    var tools = getTools();

    var html = "";
    html += "<div class='d_z adtitle'><div class='fl dw30'>插入音乐</div><div class='fr fwn dw60 tar'><span class='d_z adbtn' data-f='yinyueqingkong()'>清除音乐</span><span class='d_z adbtn' data-f='webzifanhui()'>返回</span></div></div>";
    html += "<select class='d_z adyinyue'>";
    var ms = "102053195,突然好想你,1383715,不再联系,22836,不是因为寂寞,7016921,贝加尔湖畔,5266731,传奇,102350727,车站,2651369,Yesterday Once More,6544888,恋人心,7109361,明天 你好,944319,那个男人,5018140,一不小心,101099682,奇妙能力歌,102388362,My Sunshine,314621,Because Of You ,3572709,滴答,4991941,当有天老去,103459,怒放的生命,390898,风吹麦浪,390898,回忆的的沙漏,577166,好久不见,659572,鸿雁,4830000,剪爱,5200503,卷珠帘,1250002,慢慢,777379,梦中的婚礼,9125077,你是我的眼,103459,怒放的生命,839925,时间都去哪儿呢,1313844,The Sound Of Silence,6589366,You Can Rely On Me,5598715,Hello You Beautiful Thing,7212480,斑马 斑马,7223790,我相信,9125077,你是我的眼,659572,鸿雁,9103820,匆匆那年,7223443,相信我,4602,朋友,4830471,阳光总在风雨后,123674,光辉岁月,410316,青花瓷,4829324,龙卷风,102698215,千里之外 ,5602949,生日快乐,4830471,阳光总在风雨后,875060,在路上,630586,婚礼进行曲".split(',');

    for (var i = 0; i < ms.length / 2; i++) {
        html += "<option value='"+ms[i*2]+"'>"+ms[i*2+1]+"</option>";
    }
    html += "</select></br>";
    html += "<span class='d_z adbtn' data-f='yinyuequeding()'>确定</span>";
    html += "";
    html += "<span class='d_z adbtn' data-f='webzifanhui()'>返回</span></br>";


    tools.empty();
    tools.html(html);
    bindWenZiClick();
}

function btnShiPin() {
    showTool();
    var tools = getTools();

    var html = "";
    html += "<div class='d_z adtitle'>插入视频地址(请长按地址框粘贴)</div>";
    //placehoder='请长按此粘贴!'
    html += "<textarea class='d_z adtextarea' placehoder='请长按此粘贴!'><iframe height=300 width='100%' src=\"http://player.youku.com/embed/XMTM3MDcxNTA2MA==\" frameborder=0 allowfullscreen></iframe></textarea></br>";
    html += "<span class='d_z adbtn' data-f='shipinqueding()'>确定</span>";
    html += "<span class='d_z adbtn' data-f='shipinqingkong()'>清空</span>";
    html += "<span class='d_z adbtn' data-f='webzifanhui()'>返回</span></br>";

    html += "<div class='d_z adcontent'>请插入优酷，土豆，腾讯等网站的通用代码或者html代码。<hr>";
    html += "步骤：</br>";
    html += "1、在电脑上打开优酷视频，点开分享右边的箭头，复制通用代码</br>";
    html += "2、把代码发到手机上，比如发到手机QQ，再到手机上复制代码，粘贴到此处</br><hr></div>";

    tools.empty();
    tools.html(html);
    bindWenZiClick();
}

function shipinqingkong() {
    var content = getContent();
    content.val("");
}



function btnTuPian() {
    showTool();
    var tools = getTools();

    var html = "";
    html += "<div class='d_z adtitle'>插入图片(点击插入图片)</div>";
    
    //加载用户更多图片
    html += "<div class='d_z adimages'></div>";

    html += "<span class='d_z adbtn file'>上传<input type=\"file\" /></span>";
    html += "<span class='d_z adbtn file' data-f='webzifanhui()'>返回</span></br>";

    html += "<div class='d_z adcontent'>上传提示</div>";

    

    tools.empty();
    tools.html(html);
    bindWenZiClick();
}

function uploadfile(event) {
    var img_file = event.target.files[0];
    if (!img_file) {        
        return false;
    }

    if (!(/^image\/.*$/.test(img_file.type))) {
        alert('请选择文件');
        return false;
    }
    fReader = new FileReader();
    fReader.readAsDataURL(img_file);
    fReader.onload = function (e) {
        $.post("/uploadimg", { img: e.target.result }, function (ret) {
            if (ret.indexOf('|')!=-1) {
                var as = ret.split('|');
                $('.adimages').append('<img class="adimg" src="' + as[1] + '">');
            } else {
                $(".adcontent").html('上传失败');
            }
        });

        //destDom.innerHTML = '';
        //destDom.innerHTML = '<img src="' + event.target.result + '" width="200px" height="200px"/>';
    };
}
function btnGuangGao() {
    //showTool();
    //var tools = getTools();

    //var html = "";
    //html += "<div class='d_z'>添加广告</div>";
    //html += "<a href='xxxx'>广告1</a><br/>";
    //html += "<a href='xxxx'>广告2</a><br/>";
    //html += "<a href='xxxx'>广告3</a><br/>";
    //html += "<a href='xxxx'>广告4</a><br/>";
    //html += "<a href='xxxx'>广告5</a><br/>";
    //html += "<input type=button class='d_z' value='更多' />";
    //html += "<input type=button class='d_z' value='新增广告' />";
    //tools.html(html);
}



function btnDel() {
    getMenu().hide();
    removeBgColor();
    //删除自己
    p_obj.remove();
}

function btnPre() {
    getMenu().hide();
    removeBgColor();
    //查找所有之前的兄弟节点
    p_obj.prevAll().remove();
}

function btnNext() {
    getMenu().hide();
    removeBgColor();
    //查找所有之后的兄弟节点
    p_obj.nextAll().remove();
}

//滚动条变动的时候
window.onscroll = function () {
    var a = document.documentElement.scrollTop == 0 ? document.body.clientHeight : document.documentElement.clientHeight;
    var b = document.documentElement.scrollTop == 0 ? document.body.scrollTop : document.documentElement.scrollTop;
    var c = document.documentElement.scrollTop == 0 ? document.body.scrollHeight : document.documentElement.scrollHeight;
    if (a + b >= c - 30) {

        showlog("lxw");
        if ($(".adtools100").css("display") != "none") {
            var parentObj = $(".adtools100");
            if (parentObj.find(".adnexturl").length < 1) {
                return
            }
            var fun = $(".adnexturl").attr("data-h");
            if (fun) eval(fun)
        }
    }
};